#include "Def.h"
#include <sys/socket.h>
#include <arpa/inet.h>

bool SocketAddress::init_any_addr(u16 p)
{
    this->family = AF_INET;
    this->port = htons(p);
    this->u_addr = 0u;
    this->m_zero.fill(0);
    return true;
}

bool SocketAddress::init_any_port(const char *addr_str, u16 p)
{
    auto convert_res = inet_pton(AF_INET,addr_str,b_addr.data());
    if (convert_res == -1)
    {
        return false;
    }

    this->family = AF_INET;
    this->port = htons(p);
    this->m_zero.fill(0);
    
    return true;
}

/*

u32 id;
    NODE_TYPE node_type;
    CaptionType caption;
    CaptionType note;
    SocketAddress addr;
    NodePoint point;
    u32 out_id;

*/

QJsonObject serialize_node_create_info(NodeCreateInfo &info)
{
    QJsonObject obj{};
    obj.insert("id",(int)info.id);
    obj.insert("node_type",(int)info.node_type);
    obj.insert("caption",info.caption.data());
    obj.insert("note",info.note.data());
    //obj.insert("addr_family",info.addr.family);
    obj.insert("addr_ip",(int)info.addr.u_addr);
    obj.insert("addr_port",(int)info.addr.port);
    obj.insert("point_x",info.point.x);
    obj.insert("point_y",info.point.y);
    obj.insert("out_id",(int)info.out_id);

    return obj;
}

bool load_node_create_info(QJsonObject &object, NodeCreateInfo &out_info)
{
    out_info.id = object["id"].toInt();
    out_info.node_type = (NODE_TYPE)object["node_type"].toInt();
    auto caption_str = object["caption"].toString().toStdString();
    auto note_str = object["note"].toString().toStdString();
    strcpy(out_info.caption.data(),caption_str.c_str());
    strcpy(out_info.note.data(),note_str.c_str());
    out_info.addr.u_addr = (u32)object["addr_ip"].toInt();
    out_info.addr.port = (u16)object["addr_port"].toInt();
    out_info.point.x = (int)object["point_x"].toInt();
    out_info.point.y = (int)object["point_y"].toInt();
    out_info.out_id = (u32)object["out_id"].toInt();
    return true;
}
